#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib
import urllib2
import cookielib


class HttpBase(object):
    'HTTP访问基类'
    def __init__(self):
        self.cookie_jar = cookielib.CookieJar()
        self.url_opener = urllib2.build_opener(
                urllib2.HTTPCookieProcessor(self.cookie_jar))

    def _send(self, url, data=None):
        '发送一个请求并返回响应，自动处理cookie'
        if data:
            request = urllib2.Request(url, data)
        else:
            request = urllib2.Request(url)
        response = self.url_opener.open(request)
        return response

class BrowserEmulator(HttpBase):
    '模拟浏览器发送各种请求，验证网站功能'
    URL_DOMAIN = 'http://mini-project-zgl.webapp.163.com/'
    def login(self):
        '登录操作，获取Cookie'
        url= self.URL_DOMAIN + 'passport/loginproc'
        data_dict = [('username', 'gzzhaoguangluan'), ('passwd', '123456')]
        data_str = urllib.urlencode(data_dict)
        response = self._send(url, data_str)
        print response.info()

    def page_user(self):
        '用户页面'
        url= self.URL_DOMAIN + 'user'
        response = self._send(url)
        print response.info()
        #print response.read()

    def page_error_404(self):
        '访问一个不存在的页面，返回404错误'
        try:
            url= self.URL_DOMAIN + 'notexist'
            response = self._send(url)
            print response.info()
        except urllib2.HTTPError, http_e:
            print dir(http_e)
            print http_e.code

if __name__ == '__main__':
    be = BrowserEmulator()

    # 未登录状态访问需要登录权限的页面
    be.page_user()

    # 进行登录
    be.login()
    be.page_user()

    # 测试404页面
    be.page_error_404()
